package com.kly.cashmall.widget.picker;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author
 * @date 16/12/15
 */
public class BitmapSaver {

  public static BitmapSaver create() {
    return new BitmapSaver();
  }

  public String saveBitmap(String dir, final String name, final byte[] bytes, final int maxSize) {
    if (bytes == null || bytes.length == 0) {
      return "";
    }
    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    String filePath = saveBitmap(dir, name, bitmap, maxSize);
    if (bitmap != null && !bitmap.isRecycled()) {
      bitmap.recycle();
    }
    return filePath;
  }

  public String saveBitmap(String dir, String name, Bitmap bitmap, int maxSize) {
    return saveBitmap(dir, name, bitmap, maxSize, true);
  }

  public String saveBitmap(String dir, String name, Bitmap bitmap, boolean override) {
    return saveBitmap(dir, name, bitmap, 0, override);
  }

  public String saveBitmap(String dir, String name, Bitmap bitmap) {
    return saveBitmap(dir, name, bitmap, 0);
  }

  public String saveBitmap(String path, Bitmap bitmap) {
    return saveBitmap(path, bitmap, 0, true);
  }

  public String saveBitmap(String path, Bitmap bitmap, boolean override) {
    return saveBitmap(path, bitmap, 0, override);
  }

  public String saveBitmap(String path, Bitmap bitmap, int maxKB) {
    return saveBitmap(path, bitmap, maxKB, true);
  }

  /**
   * 指定最大存放大小为maxKB（KB）
   */
  public String saveBitmap(String dir, String name, Bitmap bitmap, int maxSize, boolean override) {
    File dirFile = new File(dir);
    if (dirFile.exists() || dirFile.mkdirs()) {
      String filePath = dir.endsWith("/") ? (dir + name) : (dir + "/" + name);
      return saveBitmap(filePath, bitmap, maxSize, override);
    }
    return "";
  }

  /**
   * @param override 是否覆盖原先图片
   */
  public String saveBitmap(String path, final Bitmap bitmap, final int maxKB, boolean override) {
    if (bitmap == null) {
      return "";
    }
    File file = new File(path);
    if (override) {
      if (!file.exists()) {
        try {
          if (file.getParentFile() != null) {
            file.getParentFile().mkdirs();
          }
          file.createNewFile();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    } else {
      if (file.exists()) {
        return file.getPath();
      }
    }
    try {
      int options = BitmapUtil.zoomBitmap(bitmap, maxKB * 1024);
      if (options == 100) {
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
      } else {
        compressBitmapToFile(bitmap, file, maxKB, options);
      }
      return file.getPath();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * 压缩不改变像素大小，所以读取出来的bitmap大小还是原来的，但是可以节省空间，读取加快
   */
  private void compressBitmapToFile(Bitmap bmp, File file, int maxKB, int initOptions) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int options = initOptions;
    bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
    // 为防止失真严重，理论上压缩不小于50%
    while (options > 50 && baos.size() / 1024 > maxKB) {
      baos.reset();
      options -= 20;
      bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
    }
    try {
      BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
      fos.write(baos.toByteArray());
      fos.flush();
      fos.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
